package com.toidep.fragment.others;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.adapters.AlbumAdapter;
import com.toidep.adapters.ArticleAdapter;
import com.toidep.adapters.ModelAdapter;
import com.toidep.adapters.VideoAdapter;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.utilities.DialogUtility;
import com.toidep.widgets.sectionlist.AmazingListView;

public class SearchFragment extends BaseFragment implements OnClickListener {

	private View view;

	private MainActivity mainActivity;
	
	private RelativeLayout layoutSearch;
	private EditText edtSearch;
	private TextView buttonClear;
	
	private ModelAdapter modelAdapter;
	private VideoAdapter videoAdapter;
	private AlbumAdapter albumAdapter;
	private ArticleAdapter newsAdapter, storyAdapter, eventAdapter;
	
	private final int[] layoutButtons = new int[] {
			R.id.layoutButtonModel, R.id.layoutButtonVideo, R.id.layoutButtonAlbum,
			R.id.layoutButtonNews//, R.id.layoutButtonStory, R.id.layoutButtonEvent
	};
	
	private int[] layouts = new int[] {
			R.id.layoutModel, R.id.layoutVideo, R.id.layoutAlbum,
			R.id.layoutNews, R.id.layoutStory, R.id.layoutEvent
	};
	
	private int[] amazingListViews = new int[] {
			R.id.amazingListViewModel, R.id.amazingListViewVideo, R.id.amazingListViewAlbum,
			R.id.amazingListViewNews, R.id.amazingListViewStory, R.id.amazingListViewEvent
	};
	
	private int currentViewSelected = 0;
	private boolean isSearchFollowTag = false;
	private String keyword = "";
	
	public static SearchFragment newInstance(String keyword, int tabMode, boolean isSearchFollowTag) {
		SearchFragment myFragment = new SearchFragment();
		myFragment.setValues(tabMode, isSearchFollowTag, keyword);

		return myFragment;
	}
	
	/**
	 * Set lai cac base value cho fragment: cac item cua thanh header, currentCategory cua menuSideBar
	 */
	public void setBaseValues() {
		mainActivity.currentCategory = Constants.CATEGORY_SEARCH;
		mainActivity.mainFragment.setTittle(mainActivity.getString(R.string.label_category_search));
		mainActivity.mainFragment.showButtonSlide(false);
		mainActivity.mainFragment.showSearchLayout(true);
	}
	
	/**
	 * Set lai cac base value cho fragment: cac item cua thanh header, currentCategory cua menuSideBar
	 */
	public void setValues(int tabMode, boolean isSearchFollowTag, String content) {
		this.isSearchFollowTag = isSearchFollowTag;
		this.currentViewSelected = tabMode;
		this.keyword = content;
	}
	
	public void setTabMode(int tabMode) {
		this.currentViewSelected = tabMode;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_search, container, false);

		mainActivity = (MainActivity) getActivity();

		initComponents();
		
		setBaseValues();
		
		invisibleView(currentViewSelected);
		
		if (isSearchFollowTag) {
			edtSearch.setText(keyword);
			switchViewTab(currentViewSelected);
		}
		
		initSearchBox();
		
		return view;
	}

	private void initComponents() {
		layoutSearch = mainActivity.mainFragment.getSearchLayout();
		edtSearch = (EditText) layoutSearch.findViewById(R.id.edtSearch);
		buttonClear = (TextView) layoutSearch.findViewById(R.id.buttonClear);
		
		buttonClear.setOnClickListener(this);
		buttonClear.setVisibility(View.GONE);
		
		for (int i = 0; i < layoutButtons.length; i++)
			((RelativeLayout) view.findViewById(layoutButtons[i])).setOnClickListener(this);
	}
	
	private void invisibleView(int tabIndex) {
		// Menu color
		((RelativeLayout) view.findViewById(layoutButtons[tabIndex])).setBackgroundResource(R.drawable.bg_red_normal);
		for (int i = 0; i < layoutButtons.length; i++) {
			if (i != tabIndex)
				((RelativeLayout) view.findViewById(layoutButtons[i])).setBackgroundResource(R.drawable.bg_horizontal_button_menu);
		}
		
		// Layout content
		((RelativeLayout) view.findViewById(layouts[tabIndex])).setVisibility(View.VISIBLE);
		for (int i = 0; i < layouts.length; i++) {
			if (i != tabIndex)
				((RelativeLayout) view.findViewById(layouts[i])).setVisibility(View.GONE);
		}
	}
	
	private void switchViewTab(int currentViewSelected) {
		this.currentViewSelected = currentViewSelected;
		
		invisibleView(currentViewSelected);
			
		// Request data
		requestData();
	}
	
	private void searching(String keyword) {
		this.keyword = keyword;
		if (isValidated()) 
			switchViewTab(currentViewSelected);
		else 
			DialogUtility.showDialogAlert(mainActivity, null, getResources().getString(R.string.text_empty_search_key), "OK", null);
	}
	
	private AmazingListView modelAmazingListView, videoAmazingListView, albumAmazingListView, newsAmazingListView;
	
	private void requestData() {
		if (!isValidated())
			return;
		
		hideKeyBoard(edtSearch);
		
		switch (currentViewSelected) {
		case 0:
			if (modelAmazingListView == null) {
				modelAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
				modelAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
			}
			modelAmazingListView.setAdapter(modelAdapter = new ModelAdapter(this, Constants.CATEGORY_SEARCH, keyword));
			
			modelAdapter.setAmazingListView(modelAmazingListView, ConfigUtility.PAGE_SIZE);
			modelAdapter.notifyMayHaveMorePages();
			
			// Chuyen toi detail
			modelAmazingListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					if (modelAdapter != null && position >= 0) {
						modelAdapter.onItemClick(position);
					}
				}
			});
			
			modelAdapter.resetList();
			break;
		case 1:
			if (videoAmazingListView == null) {
				videoAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
				videoAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
			}
			videoAmazingListView.setAdapter(videoAdapter = new VideoAdapter(this, Constants.CATEGORY_SEARCH, keyword));
			videoAdapter.setAmazingListView(videoAmazingListView, ConfigUtility.PAGE_SIZE);
			videoAdapter.notifyMayHaveMorePages();
			
			// Chuyen toi detail
			videoAmazingListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					if (videoAdapter != null && position >= 0) {
						videoAdapter.onItemClick(position);
					}
				}
			});
			
			videoAdapter.resetList();
			break;
		case 2:
			if (albumAmazingListView == null) {
				albumAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
				albumAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
			}
			albumAmazingListView.setAdapter(albumAdapter = new AlbumAdapter(this, Constants.CATEGORY_SEARCH, keyword));
			
			albumAdapter.setAmazingListView(albumAmazingListView, ConfigUtility.PAGE_SIZE);
			albumAdapter.notifyMayHaveMorePages();
			
			// Chuyen toi detail
			albumAmazingListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					if (albumAdapter != null && position >= 0) {
						albumAdapter.onItemClick(position);
					}
				}
			});
			
//			albumAdapter.setAvatarImageSize();
			albumAdapter.resetList();
			break;
		case 3:
			if (newsAmazingListView == null) {
				newsAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
				newsAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
			}
			newsAmazingListView.setAdapter(newsAdapter = new ArticleAdapter(this, Constants.CATEGORY_SEARCH, Constants.ARTICLE_MODE_NEWS, keyword));
			
			newsAdapter.setAmazingListView(newsAmazingListView, ConfigUtility.PAGE_SIZE);
//			newsAdapter.notifyMayHaveMorePages();
			
			// Chuyen toi detail
			newsAmazingListView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					if (newsAdapter != null && position >= 0) {
						newsAdapter.onItemClick(position);
					}
				}
			});
			
			newsAdapter.setAvatarImageSize();
			newsAdapter.resetList();

			break;
//		case 4:
//			AmazingListView storyAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
//			storyAmazingListView.setAdapter(storyAdapter = new ArticleAdapter(this, Constants.CATEGORY_SEARCH, Constants.ARTICLE_MODE_STORY, keyword));
//			storyAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
//			
//			storyAdapter.setAmazingListView(storyAmazingListView, ConfigUtility.PAGE_SIZE);
//			storyAdapter.notifyMayHaveMorePages();
//			
//			// Chuyen toi detail
//			storyAmazingListView.setOnItemClickListener(new OnItemClickListener() {
//				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//					if (storyAdapter != null && position >= 0) {
//						storyAdapter.onItemClick(position);
//					}
//				}
//			});
//			
//			storyAdapter.setAvatarImageSize();
//			storyAdapter.resetList();
//			break;
//		case 5:
//			AmazingListView eventAmazingListView = (AmazingListView) view.findViewById(amazingListViews[currentViewSelected]);
//			eventAmazingListView.setAdapter(eventAdapter = new ArticleAdapter(this, Constants.CATEGORY_SEARCH, Constants.ARTICLE_MODE_EVENT, keyword));
//			eventAmazingListView.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
//			
//			eventAdapter.setAmazingListView(eventAmazingListView, ConfigUtility.PAGE_SIZE);
//			eventAdapter.notifyMayHaveMorePages();
//			
//			// Chuyen toi detail
//			eventAmazingListView.setOnItemClickListener(new OnItemClickListener() {
//				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//					if (eventAdapter != null && position >= 0) {
//						eventAdapter.onItemClick(position);
//					}
//				}
//			});
//			
//			eventAdapter.setAvatarImageSize();
//			eventAdapter.resetList();
//			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layoutButtonModel:
			switchViewTab(0);
			break;
		case R.id.layoutButtonVideo:
			switchViewTab(1);
			break;
		case R.id.layoutButtonAlbum:
			switchViewTab(2);
			break;
		case R.id.layoutButtonNews:
			switchViewTab(3);
			break;
//		case R.id.layoutButtonStory:
//			switchTab(4);
//			break;
//		case R.id.layoutButtonEvent:
//			switchTab(5);
//			break;
			
		case R.id.buttonClear:
			if (edtSearch != null) {
				edtSearch.setText("");
				buttonClear.setVisibility(View.GONE);
			}
			break;
		}
	}
	
	public void refresh() {
		if (currentViewSelected != -1) {
			edtSearch.setText(keyword);
			switchViewTab(currentViewSelected);
		}
	}
	
	private boolean isValidated() {
		return (keyword != null && keyword.length() > 0);
	}
	
	private void initSearchBox() {
		// Khoi tao box search
		if (edtSearch.requestFocus()) {
			InputMethodManager imanager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
			imanager.showSoftInput(edtSearch, 0);
		}
		
		String s = edtSearch.getText().toString();
		if ((s == null) || (s.length() == 0)) {
			buttonClear.setVisibility(View.GONE);
		} else {
			buttonClear.setVisibility(View.VISIBLE);
		}
		
		edtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				// Update clear button
				if ((s == null) || (s.length() == 0)) {
					buttonClear.setVisibility(View.GONE);
				} else {
					buttonClear.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

			@Override
			public void afterTextChanged(Editable s) { }
		});

		// event search function key selected
		edtSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_SEARCH || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

					searching(v.getText().toString());

					return false;
				} else {
					return false;
				}
			}
		});
		
	}

	public void hideKeyBoard(EditText editText) {
		if (editText != null) {
			((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	//#304-start
	@Override
	public void onDestroyView() {
		hideKeyBoard(edtSearch);
		super.onDestroyView();
	}
	//#304-end
}
